package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Arrays;

/**
 * 设备表Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-13
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setCurrentPage(1);
        queryProductListRequest.setPageSize(100);
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductListResponse response;
        try {
           response = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            throw new BaseException("拉倒吧");
        }
        if (response.getBody().getSuccess().equals(false)){
            throw new BaseException("拉倒吧");
        }
        // 获取产品列表
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonStr(productInfo));


    }

    @Override
    public List<ProductVo> allProduct() {
        // 从redis中查询数据
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        // 如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        // 解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public AjaxResult register(DeviceDto dto) {
        // 查询数据库，查看是否有名字相同的设备
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getNickname, dto.getNickname());
        Long count = count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error("设备名称已存在");
        }
        // 保存设备到iot平台
        RegisterDeviceRequest request = dto.getRegisterDeviceRequest();// 注册设备请求
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());// 实例ID
        RegisterDeviceResponse response;
        try {

            response = client.registerDevice(request);

        } catch (Exception e) {
            throw new BaseException("设备注册失败");
        }

        //判断是否添加成功
        if (response.getBody().getSuccess().equals(false)){
            return AjaxResult.error("设备注册失败");
        }

        // 查询设备信息
        QueryProductRequest productRequest = new QueryProductRequest();
        productRequest.setProductKey(dto.getProductKey());
        productRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductResponse productResponse;
        try {
            productResponse = client.queryProduct(productRequest);
        } catch (Exception e) {
            throw new BaseException("设备注册失败");
        }

        // 判断是否添加成功
        if (productResponse.getBody().getSuccess().equals(false)){
            return AjaxResult.error("设备注册失败");
        }

        // 设置产品名称到设备对象
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setProductName( productResponse.getBody().getData().getProductName());
        device.setIotId(response.getBody().getData().getIotId());
        device.setCreateTime(DateUtils.getNowDate());


        //物理位置
        if (device.getLocationType().equals(0)){
            device.setPhysicalLocationType(String.valueOf(-1));
        }

        //补全设备ID
        device.setIotId(response.getBody().getData().getIotId());



        try {
            deviceMapper.insertDevice(device);
        } catch (Exception e) {
            //删除IOT中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setProductKey(dto.getProductKey());
            deleteDeviceRequest.setDeviceName(response.getBody().getData().getDeviceName());
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            deleteDeviceRequest.setIotId(response.getBody().getData().getIotId());

            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("shabi4");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        return AjaxResult.success();
    }


    /**
     * 查询设备详细信息
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto dto) {
        // 查询IOT平台
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotId(dto.getIotId());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;
        try {
            response  = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("设备信息查询失败");
        }

        //安全校验
        if (response.getBody().getSuccess().equals(false)){
            throw new BaseException("设备信息查询失败");
        }

        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, dto.getIotId()));


        //合并数据
        DeviceVo deviceVo = BeanUtil.toBean(dto, DeviceVo.class);
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());// 忽略空值


        return deviceVo;
    }

    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
           response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("查询物模型失败");
        }
        if (response.getBody().getSuccess().equals(false)){
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }

    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response  =  client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("查询设备属性失败");
        }
        if (!response.getBody().success){
            throw new  BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }

}

